package com.party.web.biz.analysis;

import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.analysis.StatisticsEvent;
import com.party.core.model.analysis.StatisticsEventFlow;
import com.party.core.service.analysis.IStatisticsEventFlowService;
import com.party.core.service.analysis.IStatisticsEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: Project
 * @description: 统计事件流程业务接口实现
 * @author: Huaqunhao
 * @create: 2018-08-10 10:50
 **/
@Service
public class StatisticalEventFlowBizService {
    @Autowired
    private IStatisticsEventFlowService statisticsEventFlowService;
    @Autowired
    private IStatisticsEventService statisticsEventService;
    @Autowired
    private StringJedis stringJedis;

    private static String SUBSCRIBE_SUCCESS_CODE = "subscribeSuccess";

    /**
     * 关注成功事件写入
     *
     * @param openId openid
     */
    public void focusSuccessEventWrite(String openId) {
        String uniqueCode = stringJedis.getValue(Constant.ATTENTION_UNIQUE_CODE_KEY + openId);
        if (StringUtils.isEmpty(uniqueCode)) {
            throw new BusinessException(PartyCode.IS_NO_DATA, openId + "的uniqueCode为空");
        }
        StatisticsEvent focusSuccess = statisticsEventService.getByCode(SUBSCRIBE_SUCCESS_CODE);
        if (null == focusSuccess) {
            throw new BusinessException(PartyCode.IS_NO_DATA, "关注成功事件不存在");
        }
        StatisticsEventFlow lastFlow = statisticsEventFlowService.getNewFlow(uniqueCode);
        if (lastFlow == null) {
            throw new BusinessException(PartyCode.IS_NO_DATA, "上一个事件流程为空");
        }
        StatisticsEventFlow currentFlow = new StatisticsEventFlow();
        String parentIds = lastFlow.getParentIds();
        if (StringUtils.isEmpty(parentIds)) {
            currentFlow.setParentIds(lastFlow.getEventId());
        } else {
            currentFlow.setParentIds(lastFlow.getParentIds() + "," + lastFlow.getEventId());
        }
        //设置当前节点
        currentFlow.setUserId(lastFlow.getUserId());
        currentFlow.setParentId(lastFlow.getEventId());
        currentFlow.setPartnerId(lastFlow.getPartnerId());
        currentFlow.setEventId(focusSuccess.getId());
        currentFlow.setUniqueCode(uniqueCode);
        currentFlow.setUserId(lastFlow.getUserId());
        statisticsEventFlowService.insert(currentFlow);
    }
}
